/*************************************************************************
 *                    free                     *
 *************************************************************************
 *************************************************************************
 * Filename	   : package_length.c
 * Description   : This file is used to know the length of the packages
 * Version	   : 1.0
 * History       :
 free 2013-4-3  Create
 *************************************************************************/

#include <stdio.h>

#define PACKAGE_LENGTH_188 188
#define PACKAGE_LENGTH_204 204

/*************************************************************************
 * Function Name : Check10Times
 * Description   : check length 10 times and seek to current position
 * Parameters    :
 *                pTsFile -- File Pointer
 *                liLength -- Predicted package length
 *                liOffset -- Current offset
 * Returns       : 0 - Failed, 1 - Positive
 **************************************************************************/
static int Check10Times(FILE *pTsFile, int iLength, long int liOffset)
{
	int iTime = 0;
	int iTemp = 0;

	for (iTime = 0; iTime < 10; iTime++)
	{
		if (fseek(pTsFile, iLength - 1, SEEK_CUR) != 0)
		{
			if (fseek(pTsFile, liOffset, SEEK_SET) != 0)
			{
				printf("File read error!\n");
			}
			return 0;
		}
		iTemp = fgetc(pTsFile);
		if (iTemp == 0x47)
		{
			continue;
		}
		if (iTemp == EOF)
		{
			printf("File read error!\n");
		}
		if (fseek(pTsFile, liOffset, SEEK_SET) != 0)
		{
			printf("File read error!\n");
		}
		return 0;
	}
	//printf("This is a %d byte package TS file!\n", iLength);
	return 1;
}

/*************************************************************************
 * Function Name : GetPackageLength
 * Description   : get the package length
 * Parameters    :
 *                pTsFile -- File Pointer
 * Returns       : 0 - error	188 - 188 byte package	204 - 204 byte package
 **************************************************************************/
int GetPackageLength(FILE *pTsFile, long int *liFirstPackageOffset)
{
	int iTemp = 0;
	long int liOffset = 0;

	while (iTemp != EOF)
	{
		iTemp = fgetc(pTsFile);
		if (iTemp != 0x47)
		{
			continue;
		}
		liOffset = ftell(pTsFile);
		if (Check10Times(pTsFile, PACKAGE_LENGTH_188, liOffset))
		{
			*liFirstPackageOffset = liOffset - 1;
			return PACKAGE_LENGTH_188;
		}
		if (Check10Times(pTsFile, PACKAGE_LENGTH_204, liOffset))
		{
			*liFirstPackageOffset = liOffset - 1;
			return PACKAGE_LENGTH_204;
		}
	}
	printf("File read error!\n");
	return 0;
}

